package legumes.client.ui.widgets.form.item;

import java.util.List;

import legumes.shared.domain.PlaceDelivery;
import legumes.shared.domain.Store;

import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.validator.CustomValidator;

public class PlacesDeliverySelectItem extends SelectItem {
	
	private PlaceDelivery [] pdAr;
	private PlaceDelivery selectedPd;
	
	public PlacesDeliverySelectItem(Store selectedStore_){
		super("PlaceDeliverySelectItem", "Lieux de livraison");
		setValue("Loading...");
		setShowTitle(false);
		setWidth(200);
		setTextAlign(Alignment.LEFT);
		setValidateOnExit(true);
		setValidateOnChange(true);
        setValidators(new CustomValidator(){

			@Override
			protected boolean condition(Object value) {
				PlaceDelivery pdFound = findPlaceDelivery(value.toString());
				selectedPd = pdFound;
				return selectedPd != null;
			}
			
		});
        refreshStoreList(selectedStore_.getPlaceDeliveryList(), null);
	}
	
	public PlaceDelivery findPlaceDelivery(String pdTitle_){
		for(PlaceDelivery pd : pdAr){
			if( pd.getTitle().equalsIgnoreCase(pdTitle_ ) ){
				return pd;
			}
		}
		return null;
	}

	public PlaceDelivery getSelectedPlaceDelivery() {
		return selectedPd;
	}
	
	
	public void refreshStoreList(List<PlaceDelivery> pdList_, String pdTitleToSelect_){
		pdAr = pdList_.toArray(new PlaceDelivery[0]);
		if(pdList_.size()>0){
			String [] strAr = PlaceDelivery.createPlaceDeliveryNameArray( pdList_ );
			setValueMap(strAr);
			int indexPdToSelect = PlaceDelivery.findPlaceDelivery(strAr, pdTitleToSelect_ );
			int realIndexPdToSelect = indexPdToSelect<0?0:indexPdToSelect;
			setSelectedPlaceDelivery( pdAr[realIndexPdToSelect] );
		} else {
			setValue("");
		}
	}
	
	public void setSelectedPlaceDelivery(PlaceDelivery pd_){
		selectedPd = pd_;
		setValue(pd_.getTitle());
	}
	
}
